//! 安全管理器
//! 
//! 提供统一的安全管理功能，包括：
//! - 认证管理
//! - 授权控制
//! - 权限管理
//! - 安全审计

use std::collections::HashMap;
use std::sync::Arc;
use serde::{Deserialize, Serialize};
use tokio::sync::RwLock;

use crate::error::{KernelError, Result};

/// 认证上下文
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthContext {
    /// 用户ID
    pub user_id: String,
    /// 用户名
    pub username: String,
    /// 用户角色
    pub roles: Vec<String>,
    /// 权限列表
    pub permissions: Vec<Permission>,
    /// 会话ID
    pub session_id: String,
    /// 认证时间
    pub authenticated_at: chrono::DateTime<chrono::Utc>,
    /// 过期时间
    pub expires_at: Option<chrono::DateTime<chrono::Utc>>,
    /// 自定义属性
    pub attributes: HashMap<String, String>,
}

/// 权限定义
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Permission {
    /// 资源类型
    pub resource: String,
    /// 操作类型
    pub action: String,
    /// 资源实例（可选）
    pub instance: Option<String>,
    /// 条件（可选）
    pub conditions: Option<HashMap<String, String>>,
}

/// 安全策略
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityPolicy {
    /// 策略ID
    pub id: String,
    /// 策略名称
    pub name: String,
    /// 策略描述
    pub description: Option<String>,
    /// 策略规则
    pub rules: Vec<SecurityRule>,
    /// 是否启用
    pub enabled: bool,
    /// 优先级
    pub priority: i32,
}

/// 安全规则
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityRule {
    /// 规则ID
    pub id: String,
    /// 规则类型
    pub rule_type: SecurityRuleType,
    /// 匹配条件
    pub conditions: Vec<RuleCondition>,
    /// 执行动作
    pub action: SecurityAction,
}

/// 安全规则类型
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SecurityRuleType {
    /// 访问控制
    AccessControl,
    /// 数据过滤
    DataFilter,
    /// 审计日志
    AuditLog,
    /// 限流控制
    RateLimit,
}

/// 规则条件
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RuleCondition {
    /// 字段名
    pub field: String,
    /// 操作符
    pub operator: ConditionOperator,
    /// 值
    pub value: String,
}

/// 条件操作符
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ConditionOperator {
    Equals,
    NotEquals,
    Contains,
    StartsWith,
    EndsWith,
    GreaterThan,
    LessThan,
    In,
    NotIn,
    Regex,
}

/// 安全动作
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SecurityAction {
    /// 允许
    Allow,
    /// 拒绝
    Deny,
    /// 记录日志
    Log,
    /// 限流
    RateLimit { max_requests: u32, window_seconds: u32 },
    /// 自定义动作
    Custom(String),
}

/// 安全审计事件
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityAuditEvent {
    /// 事件ID
    pub id: String,
    /// 事件类型
    pub event_type: SecurityEventType,
    /// 用户ID
    pub user_id: Option<String>,
    /// 资源
    pub resource: String,
    /// 操作
    pub action: String,
    /// 结果
    pub result: SecurityResult,
    /// 事件时间
    pub timestamp: chrono::DateTime<chrono::Utc>,
    /// 客户端IP
    pub client_ip: Option<String>,
    /// 用户代理
    pub user_agent: Option<String>,
    /// 附加信息
    pub details: HashMap<String, String>,
}

/// 安全事件类型
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SecurityEventType {
    Authentication,
    Authorization,
    DataAccess,
    ConfigChange,
    SystemAccess,
}

/// 安全结果
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SecurityResult {
    Success,
    Failure,
    Blocked,
    Warning,
}

/// 安全管理器
pub struct SecurityManager {
    /// 安全策略
    policies: Arc<RwLock<HashMap<String, SecurityPolicy>>>,
    /// 审计事件
    audit_events: Arc<RwLock<Vec<SecurityAuditEvent>>>,
    /// 认证提供者
    auth_providers: Arc<RwLock<Vec<Arc<dyn AuthProvider>>>>,
    /// 授权提供者
    authz_providers: Arc<RwLock<Vec<Arc<dyn AuthzProvider>>>>,
}

/// 认证提供者接口
#[async_trait::async_trait]
pub trait AuthProvider: Send + Sync {
    /// 提供者ID
    fn id(&self) -> &str;
    
    /// 认证用户
    async fn authenticate(&self, credentials: &Credentials) -> Result<AuthContext>;
    
    /// 验证令牌
    async fn validate_token(&self, token: &str) -> Result<AuthContext>;
    
    /// 刷新令牌
    async fn refresh_token(&self, refresh_token: &str) -> Result<String>;
    
    /// 注销
    async fn logout(&self, session_id: &str) -> Result<()>;
}

/// 授权提供者接口
#[async_trait::async_trait]
pub trait AuthzProvider: Send + Sync {
    /// 提供者ID
    fn id(&self) -> &str;
    
    /// 检查权限
    async fn check_permission(
        &self,
        auth_context: &AuthContext,
        permission: &Permission,
    ) -> Result<bool>;
    
    /// 获取用户权限
    async fn get_user_permissions(&self, user_id: &str) -> Result<Vec<Permission>>;
    
    /// 过滤数据
    async fn filter_data(
        &self,
        auth_context: &AuthContext,
        data: serde_json::Value,
    ) -> Result<serde_json::Value>;
}

/// 认证凭据
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Credentials {
    /// 用户名密码
    UsernamePassword { username: String, password: String },
    /// JWT令牌
    JwtToken { token: String },
    /// API密钥
    ApiKey { key: String },
    /// OAuth2令牌
    OAuth2Token { access_token: String },
}

impl SecurityManager {
    /// 创建新的安全管理器
    pub fn new() -> Self {
        Self {
            policies: Arc::new(RwLock::new(HashMap::new())),
            audit_events: Arc::new(RwLock::new(Vec::new())),
            auth_providers: Arc::new(RwLock::new(Vec::new())),
            authz_providers: Arc::new(RwLock::new(Vec::new())),
        }
    }
    
    /// 启动安全管理器
    pub async fn start(&self) -> Result<()> {
        tracing::info!("启动安全管理器");
        
        // 加载默认安全策略
        self.load_default_policies().await?;
        
        tracing::info!("安全管理器启动完成");
        Ok(())
    }
    
    /// 注册认证提供者
    pub async fn register_auth_provider(&self, provider: Arc<dyn AuthProvider>) -> Result<()> {
        let mut providers = self.auth_providers.write().await;
        providers.push(provider);
        Ok(())
    }
    
    /// 注册授权提供者
    pub async fn register_authz_provider(&self, provider: Arc<dyn AuthzProvider>) -> Result<()> {
        let mut providers = self.authz_providers.write().await;
        providers.push(provider);
        Ok(())
    }
    
    /// 认证用户
    pub async fn authenticate(&self, credentials: &Credentials) -> Result<AuthContext> {
        let providers = self.auth_providers.read().await;
        
        for provider in providers.iter() {
            match provider.authenticate(credentials).await {
                Ok(auth_context) => {
                    // 记录认证成功事件
                    self.audit_security_event(SecurityAuditEvent {
                        id: uuid::Uuid::new_v4().to_string(),
                        event_type: SecurityEventType::Authentication,
                        user_id: Some(auth_context.user_id.clone()),
                        resource: "authentication".to_string(),
                        action: "login".to_string(),
                        result: SecurityResult::Success,
                        timestamp: chrono::Utc::now(),
                        client_ip: None,
                        user_agent: None,
                        details: HashMap::new(),
                    }).await?;
                    
                    return Ok(auth_context);
                },
                Err(_) => continue,
            }
        }
        
        // 记录认证失败事件
        self.audit_security_event(SecurityAuditEvent {
            id: uuid::Uuid::new_v4().to_string(),
            event_type: SecurityEventType::Authentication,
            user_id: None,
            resource: "authentication".to_string(),
            action: "login".to_string(),
            result: SecurityResult::Failure,
            timestamp: chrono::Utc::now(),
            client_ip: None,
            user_agent: None,
            details: HashMap::new(),
        }).await?;
        
        Err(KernelError::security("认证失败"))
    }
    
    /// 验证令牌
    pub async fn validate_token(&self, token: &str) -> Result<AuthContext> {
        let providers = self.auth_providers.read().await;
        
        for provider in providers.iter() {
            if let Ok(auth_context) = provider.validate_token(token).await {
                return Ok(auth_context);
            }
        }
        
        Err(KernelError::security("令牌验证失败"))
    }
    
    /// 检查权限
    pub async fn check_permission(
        &self,
        auth_context: &AuthContext,
        permission: &Permission,
    ) -> Result<bool> {
        let providers = self.authz_providers.read().await;
        
        for provider in providers.iter() {
            match provider.check_permission(auth_context, permission).await {
                Ok(allowed) => {
                    // 记录授权事件
                    self.audit_security_event(SecurityAuditEvent {
                        id: uuid::Uuid::new_v4().to_string(),
                        event_type: SecurityEventType::Authorization,
                        user_id: Some(auth_context.user_id.clone()),
                        resource: permission.resource.clone(),
                        action: permission.action.clone(),
                        result: if allowed { SecurityResult::Success } else { SecurityResult::Blocked },
                        timestamp: chrono::Utc::now(),
                        client_ip: None,
                        user_agent: None,
                        details: HashMap::new(),
                    }).await?;
                    
                    return Ok(allowed);
                },
                Err(_) => continue,
            }
        }
        
        // 默认拒绝
        Ok(false)
    }
    
    /// 添加安全策略
    pub async fn add_policy(&self, policy: SecurityPolicy) -> Result<()> {
        let mut policies = self.policies.write().await;
        policies.insert(policy.id.clone(), policy);
        Ok(())
    }
    
    /// 获取安全策略
    pub async fn get_policy(&self, policy_id: &str) -> Option<SecurityPolicy> {
        let policies = self.policies.read().await;
        policies.get(policy_id).cloned()
    }
    
    /// 记录安全审计事件
    pub async fn audit_security_event(&self, event: SecurityAuditEvent) -> Result<()> {
        let mut events = self.audit_events.write().await;
        events.push(event);
        
        // 限制审计事件数量
        if events.len() > 100000 {
            events.remove(0);
        }
        
        Ok(())
    }
    
    /// 获取审计事件
    pub async fn get_audit_events(&self, limit: Option<usize>) -> Vec<SecurityAuditEvent> {
        let events = self.audit_events.read().await;
        
        match limit {
            Some(n) => {
                let start = if events.len() > n { events.len() - n } else { 0 };
                events[start..].to_vec()
            },
            None => events.clone(),
        }
    }
    
    /// 加载默认安全策略
    async fn load_default_policies(&self) -> Result<()> {
        let default_policy = SecurityPolicy {
            id: "default".to_string(),
            name: "默认安全策略".to_string(),
            description: Some("系统默认的安全策略".to_string()),
            rules: vec![
                SecurityRule {
                    id: "admin-access".to_string(),
                    rule_type: SecurityRuleType::AccessControl,
                    conditions: vec![
                        RuleCondition {
                            field: "role".to_string(),
                            operator: ConditionOperator::Equals,
                            value: "admin".to_string(),
                        }
                    ],
                    action: SecurityAction::Allow,
                }
            ],
            enabled: true,
            priority: 100,
        };
        
        self.add_policy(default_policy).await?;
        Ok(())
    }
}

impl Permission {
    /// 创建新权限
    pub fn new(resource: String, action: String) -> Self {
        Self {
            resource,
            action,
            instance: None,
            conditions: None,
        }
    }
    
    /// 设置资源实例
    pub fn with_instance(mut self, instance: String) -> Self {
        self.instance = Some(instance);
        self
    }
    
    /// 添加条件
    pub fn with_condition(mut self, key: String, value: String) -> Self {
        self.conditions.get_or_insert_with(HashMap::new).insert(key, value);
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    
    #[tokio::test]
    async fn test_security_manager() {
        let security_manager = SecurityManager::new();
        security_manager.start().await.unwrap();
        
        // 测试权限创建
        let permission = Permission::new("database".to_string(), "read".to_string())
            .with_instance("users".to_string())
            .with_condition("department".to_string(), "engineering".to_string());
        
        assert_eq!(permission.resource, "database");
        assert_eq!(permission.action, "read");
        assert_eq!(permission.instance, Some("users".to_string()));
        
        // 测试安全策略
        let policies = security_manager.policies.read().await;
        assert!(policies.contains_key("default"));
    }
}
